/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin;

import app.Const;
import app.models.DaoKit;
import app.models.info.Floor;
import app.models.info.ShoppingMall;
import app.models.parking.Parking;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.BooleanUtils;

import java.util.List;

/**
 * <p>
 * 楼层管理.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-04-08 13:01
 * @since JDK 1.6
 */
public class FloorController extends BasicController {

    public static final String FORM_ATTR = "floor";

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        final Page<Record> floorPage = Floor.dao.datatable(criterias);
        renderDataTables(floorPage, criterias);
    }


    public void create() {
        Floor floor = new Floor();
        setAttr(FORM_ATTR, floor);
        setAttr("mallblock", ShoppingMall.dao.malllist());
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }


    public void edit() {
        Floor floor = Floor.dao.findById(getPara());

        setAttr(FORM_ATTR, floor);
        setAttr("mallblock", ShoppingMall.dao.malllist());
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        render("item.ftl");
    }


    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("floor.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }


    public void save() {
        final Floor floor = getModel(Floor.class);
        floor.set("parking", BooleanUtils.toBooleanObject(getPara("parking", "off")));
        if (DaoKit.isNew(floor)) {
            // create parking with floor
            floor.save();

            Parking.dao.batchWithFloor(floor);
        } else {
            floor.update();
        }
        redirect("/admin/floor");
    }
}